package com.example.ljdemo.infrastructure.responce;

import com.example.ljdemo.infrastructure.util.MsgUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @author jingjing.dong
 * @since 2021/3/21-16:47
 */
@Setter
@Getter
@ToString
public
class Echo<T> {
    private T data;
    private String state;
    private String errmsg;
    public Echo(String errmsg) {
        this.state = "false";
        this.data = (T) new String[0];
        this.errmsg = errmsg;
    }

    public Echo(T data, String errmsg) {
        this.data = data;
        this.errmsg = errmsg;
    }
    public Echo(T data, String state, String errmsg) {
        this.data = data;
        this.state = state;
        this.errmsg = errmsg;
    }

    public static <T> Echo<T> success(T data) {
        if(null!=data&&data.toString().indexOf("error")>-1){
            if(data.toString().indexOf("status=401")>-1){
                return  Echo.error("token失效!需要重新登录");
            }
            return Echo.error(data.toString());
        }

        return new Echo<>(data, "true", "");
    }

    public static <T> Echo<T> success(String msg) {
        return new Echo<>((T)new String[0],"true", msg);
    }
    public static <T> Echo<T> error(String msg) {
        return new Echo<>((T)new String[0], "false", msg);
    }
    public static Echo<?> fail(ErrorCode code, String... variables) {
        return new Echo<>(code.getCode()+""+ MsgUtils.getMessage(code.name(), variables));
    }
}
